import {Modal, Select, message, Form, Table, Radio} from 'antd'
import React, {useEffect, useState} from "react";
import { apiInterceptors, distributePermission, getPermissionByRole, getRoleById, getApplication, addPermissions } from '@/client/api';
const permissionDistribute = ({ setModal, roleId, successCall }:any) => {
  const [permissionForm] = Form.useForm();
  const options = [


    {label: '应用只读', value: '4'},
    {label: '应用管理员', value: '3'},

    {label: '普通租户', value: '2'},
    { label: '租户管理员', value: '1' }
  ]

  const [tenantId, setTenantId] = useState('')
  const [tableData, setTableData] = useState([])
  const [selectedRows, setSelectedRows] = useState([])
  const [permissionValue, setPermissionValue] = useState('')
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const columns = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '权限',
      dataIndex: 'appAction',
      key: 'appAction',
      render: (_:any, record: any) => {
        return(
        <Radio.Group onChange={(e) => onChange(e, record)} defaultValue={record.appAction}>
          <Radio value='4'>应用只读</Radio>
          <Radio value='3'>应用管理员</Radio>
        </Radio.Group>)
      }
    }
  ]

  const getApp = async () => {
    const [_, data] = await apiInterceptors(getApplication({page_num: 1, page_size: 9999}))
    const optionList = data?.data.map((item: any) => ({ name: item.name, id: item.id, appAction: '' }))
    getRoleInfo(optionList)
  }
  const getRoleInfo = async (optionList) => {
    const [_, data] = await apiInterceptors(getRoleById(roleId))
    setTenantId(data.tenant_id)
    const permissionList = JSON.parse(data?.permissions.replace(/'/g, '"'))
    const tempArr = []
    permissionList.forEach((item:any) => {
      const index = optionList.findIndex((x:any) => x.id === item.split(':')[0])
      if (index > -1) {
        const newItem = {...optionList[index], appAction: item.split(':')[1]}
        tempArr.push(newItem)
        optionList[index] = newItem
      } else {
        setPermissionValue(item.split(':')[1])
      }
    })
    setSelectedRowKeys(tempArr.map((item:any) => item.id))
    setSelectedRows(tempArr)
    setTableData(optionList)
  }
  const submitHandle = async () => {
    let obj = {}
    for(const item of selectedRows) {
      if (!item.appAction) {
        return message.error('请选择应用对应的权限')
      }
      obj[item.id] = item.appAction
    }
    if (!permissionValue) {
      return message.error('请选择租户权限')
    }
    obj[tenantId] = permissionValue
    const param = {
      "sub_id": roleId,
      'tenant_id': tenantId,
      'app_action': obj
    }
    const [err] = await apiInterceptors(addPermissions(param))
    if (!err) {
      message.success('操作成功')
      setModal(false)
      successCall()
    }
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys)
      setSelectedRows(selectedRows)
    },
  };
  const onChange = (e, record) => {
    record.appAction = e.target.value

    setTableData(tableData.map((item: any) => {
      if (record.id === item.id) {
        return { ...item, ...record }
      }
      return item
    }))
  }
  const cancelHandle = () => {
    setModal(false)
  }
  const permissionChange = (e) => {
    setPermissionValue(e)
  }
  useEffect(() => {
    // getRolePermission()
    getApp()
  },[])
  return (<>
    <Modal
      title='权限分配'
      open={true}
      onOk={submitHandle} onCancel={cancelHandle}
      width={500}
    >
      <div style={{fontWeight: 'bold', marginTop: '10px', marginBottom: '10px'}}>租户权限</div>
      <Select
        allowClear
        placeholder="请选择租户权限"
        style={{width: '100%'}}
        options={[
          {label: '普通租户', value: '2'},
          { label: '租户管理员', value: '1' }
        ]}
        onChange={permissionChange}
        value={permissionValue}
      />
      <div style={{fontWeight: 'bold', marginTop: '20px', marginBottom: '10px'}}>应用权限</div>
      <Table
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        pagination={false}
        rowSelection={{
          hideSelectAll: true,
          ...rowSelection,
        }}
      />
    </Modal>
  </>)
}

export default permissionDistribute
